/*
Properties:
	window.ie - will be set to true if the current browser is internet explorer (any).
	window.ie6 - will be set to true if the current browser is internet explorer 6.
	window.ie7 - will be set to true if the current browser is internet explorer 7.
	window.gecko - will be set to true if the current browser is Mozilla/Gecko.
	window.webkit - will be set to true if the current browser is Safari/Konqueror.
	window.webkit419 - will be set to true if the current browser is Safari2 / webkit till version 419.
	window.webkit420 - will be set to true if the current browser is Safari3 (Webkit SVN Build) / webkit over version 419.
	window.opera - is set to true by opera itself.
*/

window.xpath = !!(document.evaluate);
if (window.ActiveXObject) window.ie = window[window.XMLHttpRequest ? 'ie7' : 'ie6'] = true;
else if (document.childNodes && !document.all && !navigator.taintEnabled) window.webkit = window[window.xpath ? 'webkit420' : 'webkit419'] = true;
else if (document.getBoxObjectFor != null) window.gecko = true;

/*compatibility*/
window.khtml = window.webkit;
/*end compatibility*/

/*
	Graceful Degradation of Firebug Console Object
	code yanked from the Yahoo media player. Thanks, Yahoo.
*/
if (typeof(window.console)=='undefined' || typeof(console.firebug) == 'undefined') {
	var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
	window.console = {};
	for (var i = 0; i <names.length; ++i) window.console[names[i]] = function() {};
};


var $$ = function(_id){
	return $('#' + _id);
};

var xpk = {};

xpk.Class = function(data){
	data = $.extend(data,{
		setOptions: function(options){
			this.options = $.extend(this.options, options || {});
			return this;
		}
	});
	return data;
};

/*
	Description:
		WMS Messages interface - used to display various messages in page context operations
	
	Usage:
		xpk.Messages.show(status, message);
			status - optional string. special statuses are 'error', 'success', 'warning'
			message - object that contains 2 keys
			message = {
				title: String
				message: String
			};
			title is optional
	
	Shorthands:
		xpk.Messages.info(message);
		xpk.Messages.success(message);
		xpk.Messages.warn(message);
		xpk.Messages.error(message);
*/
xpk.Messages = {
	bReady: false,
	delay: 40000,
	init: function(){
		this.messenger = new xpk.Growl({
			delay: this.delay,
			maxMessages: 5,
			offset: 1,
			position: {
				vertical: 'top',
				horisontal: 'right'
			}	
		});
		this.ajaxLoader = new xpk.Growl({
			className: 'ajax-loader',
			delay: 0,
			single: true,
			speed: 200,
			offset: 1,
			position: {
				vertical: 'top',
				horisontal: 'left'
			},
			onshow: function(){
				document.body.style.cursor = 'progress';
			},
			onhide: function(){
				document.body.style.cursor = '';
			}
		});		
		this.bReady = true;
	},
	show: function(_msg){		
		if(!this.bReady) this.init();
		_msg.delay =  this.delay;
		this.messenger.alert(_msg);
	},
	info: function(_msg){
		_msg.delay =  this.delay;
		_msg.status = 'info';
		this.show(_msg);
	},
	success: function(_msg){
		_msg.delay =  this.delay;
		_msg.status = 'success';
		this.show(_msg);
	},
	error: function(_msg){
		_msg.delay = 0;
		_msg.status = 'error';
		this.show(_msg);
	},
	warn: function(_msg){
		_msg.delay = 0;
		_msg.status = 'warning';
		this.show(_msg);
	},
	progress: function(_msg){
		if(!this.bReady) this.init();
		var _defaultMessage = 'Please wait...'
		this.ajaxLoader.alert({
			message: _msg || _defaultMessage
		});
	},
	inline: function(messages, id, set) {
		
	/*
		mesages = [{title: 'Error!',message: 'Something goes wrong'}]
		xpk.Messages.inline([{title: 'Error!',message: 'Something goes wrong'}], 'editPanelError');
	*/
		
        var errorWrapper = $('#' + id).css({'display':'none'}).empty();
		var messageWrapper = $('<div class="error-message"/>');
		var closeIcon = $('<a href="#close" class="close">x</a>').appendTo(errorWrapper);
		
		closeIcon.click(function(event){
			if (event.stopPropagation) event.stopPropagation();
			if (event.preventDefault) event.preventDefault();			
			errorWrapper.slideUp(200, function(){ errorWrapper.empty() });
			return false;
		});

		if(messages) {	           	   
        	var msg = [];
			var _message, _title, _text;
			
			for(var a = 0, b = messages.length; a < b; a++){
				_message = messages[a];
   	        	_title = _message.title || false;
        	    _text = _message.message;
	            _message = (_title ? '<h5>' + _title + '</h5>' : '') + '' + _text + '';
    	        msg.push(messageWrapper.clone().appendTo(errorWrapper).html(_message));
			};

			messageWrapper.remove();
			delete messageWrapper;

			errorWrapper.slideDown(300, function(){
				$(window).scrollTo( errorWrapper, { duration:500, axis:'y'});
			});
		};
		return false;
    }
};

xpk.General = {
	windowParams: {
		title: null,
		html: null,		
		hide: function(){},
		className: 'xpk-window',
		show: function(){
			this.content.setFocus();
		},
		confirm: function(){},
		cancel: function(){
			this.hide();
		}
	},
	setupSidebar: function(_sidebarID){},
	setupGrid: function(_gridBlockID, _filter){},
	getWindowParams: function(){
		return {
			title: null,
			html: null,		
			hide: function(){},
			className: 'xpk-window',
			show: function(){
				this.content.setFocus();
			},
			confirm: function(){},
			cancel: function(){
				this.hide();
			}
		};
	},
	openModalWindow: function(options){
/*
	options = {
		element: true,
		id: 'window_wrap_id',
		title: 'window_title',
		width: '550'
	};
*/
		var _this = this;
		var _id = options.id;
		
		if(options.element){
			options.element = $$(options.id);
		};
		delete options.id;
		
		if(!xpk.Windows[_id]){			
			var windowParams = $.extend(this.getWindowParams(),options);
			//delete windowParams.element;
			xpk.Windows[_id] = new xpk.Window(windowParams);
		};
		
		xpk.Windows[_id].show(options);
		return xpk.Windows[_id];
	},
	setupCheckList: function(_id, options){
		return new xpk.CheckList(_id, options);
	}
};

xpk.Helpers = {};

xpk.Helpers.dispose = function(id) {};

xpk.Helpers.shiftSelect = 	function(_list, _first, _last, _fn){};

xpk.Helpers.showPopupControl = function(_link, _id) {};

xpk.Helpers.hidePopupControl = function(_id) {};


xpk.Helpers.checkToggle = function(check, id, anime){};

xpk.Helpers.radioToggle = function(check, id, amine){};

xpk.Helpers.showContextMenu = function(element, menu){};

(function($){

	$.fn.highlight = function(color) {
		return this.each(function() {
			var $element = $(this);
			var bgColor = $element.css('backgroundColor');
			var bgStyle = $element.get(0).style.backgroundColor;
			if(bgColor == 'transparent'){
				var parent = $element.parent();
				while(parent.length && bgColor == 'transparent'){
					bgColor = parent.css('backgroundColor');
					parent = parent.parent();
				};
			};
			$element.css("backgroundColor", color)
				.animate({
					"backgroundColor": bgColor
				},{
					duration: 1000,
				complete: function(){
					this.style.backgroundColor = bgStyle;
				}
			});
		});
	};
	

	$.fn.getFormElements = function(){
		var $elements = $("input,select,textarea", this);
		return $elements;
	};

	$.fn.toQueryString = function(){
		var queryString = [];
		var elements = this.getFormElements()
		elements.each(function(el){
			var $element = $(this);
			var name = this.name;
			var value = $element.val();
			if (value === false || !name || this.disabled) return;
			var qs = function(val){
				queryString.push(name + '=' + encodeURIComponent(val));
			};
			if (typeof value === 'object' && obj.constructor === Array) $.each( value, qs );
			else qs(value);
		});
		return queryString.join('&');
	};

	$.fn.coordinates = function(_relative, _margin) {
		if ( !this[0] ) return { top: 0, left: 0, right:0, bottom: 0, width: 0, height: 0 };
		var fn = _relative ? 'position' : 'offset';
		var _position = this[fn]();
		
		fn = _margin ? 'outerWidth' : 'width';
		_position.width = this[fn]();

		fn = _margin ? 'outerHeight' : 'height';
		_position.height = this[fn]();
		
		_position.right = _position.left + _position.width;
		_position.bottom = _position.top + _position.height;
		
		return _position;
	};

	$.fn.setFocus = function(_focus) {
		return this.each(function() {
			var _textbox = $(this).find('input[type=text], select, textarea');
			for(var a = 0, b = _textbox.size(); a < b; a++){
				if(!_textbox[a].disabled && !_textbox[a].readOnly){
					if(window.ie){
						_textbox[a].value = _textbox[a].value;
					};
					_textbox[a].focus();
					return;
				};
			};
		});
	};

	$.fn.resetTextbox = function() {
		return this.each(function() {
			var _textbox = $(this);
			_textbox[0].value = '';			
			_textbox.focus();
		});
	};
	
	$.fn.disableSelection = function() {
		if (window.getSelection) window.getSelection().removeAllRanges(); 
		else if (document.selection && document.selection.clear) document.selection.clear();		
		return this.each(function() {
			this.unselectable = "on";
			this.onselectstart = function() { return false; };
			document.ondragstart = function() { return false; };
			if (this.style) this.style.MozUserSelect = "none";
		});
	};
	
	$.fn.enableSelection = function() {
		return this.each(function() {		
			this.unselectable = "off";
			this.onselectstart = null;
			document.ondragstart = null;
			if (this.style) this.style.MozUserSelect = "";
		  });
	};
	
	$.fn.lookup = function(options){
		if(!this.length) return this;
		return this.each(function(){
			var $element = $(this);
			var hasLokup = $element.data('lookup_ready');
			
			if(hasLokup) {
				xpk.Lookups[this.id].resetLookup(true);
			} else {
				new xpk.Lookup($element, options);
			};
		});
	};

	$.fn.maxChars = function(num){
		if(!this.length) return this;
		return this.each(function(){
			var $element = $(this);
			$element.keyup(function(){
				if(this.value.length > num) {
					$element.val($element.val().substr(0,num));
					return false;
				};
			});
			
		});
	};
	
	$.fn.bgIframe = $.fn.bgiframe = function(s) {
		// This is only for IE6
		if ( $.browser.msie && /6.0/.test(navigator.userAgent) ) {
			s = $.extend({
				top     : 'auto', // auto == .currentStyle.borderTopWidth
				left    : 'auto', // auto == .currentStyle.borderLeftWidth
				width   : 'auto', // auto == offsetWidth
				height  : 'auto', // auto == offsetHeight
				opacity : true,
				src     : 'javascript:false;'
			}, s || {});
			var prop = function(n){return n&&n.constructor==Number?n+'px':n;},
				html = '<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+
						   'style="display:block;position:absolute;z-index:-1;'+
							   (s.opacity !== false?'filter:Alpha(Opacity=\'0\');':'')+
							   'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+
							   'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+
							   'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+
							   'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+
						'"/>';
			return this.each(function() {
				if ( $('> iframe.bgiframe', this).length == 0 )
					this.insertBefore( document.createElement(html), this.firstChild );
			});
		}
		return this;
	};	

	$.fn.reset = function() {
		return this.each(function() {
			var type = this.type, tag = this.tagName.toLowerCase();
			var defaultValue = this.defaultValue;
			if (tag == 'form')
				return $(':input',this).reset();
			if (type == 'text' || type == 'password' || tag == 'textarea')
				this.value = defaultValue || '';
			else if (type == 'checkbox' || type == 'radio')
				this.checked = this.defaultChecked;
			else if (tag == 'select')
				this.selectedIndex = -1;
		});
	};
})(jQuery);